﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

namespace GameToolkit
{
    [RequireComponent(typeof(CapsuleCollider))]
    [AddComponentMenu("Navigation/Runtime NavMeshCapsule")]
	public class NavMeshCapsuleRT : NavMeshSource
    {
        CapsuleCollider mCapsule;

        public override Bounds localBounds
        {
            get
            {
                if (mCapsule == null)
                    mCapsule = GetComponent<CapsuleCollider>();
                var rad = mCapsule.radius * 2f;
                if (mCapsule.direction == 0)
                    return new Bounds(mCapsule.center, new Vector3(mCapsule.height, rad, rad));
                else if (mCapsule.direction == 1)
                    return new Bounds(mCapsule.center, new Vector3(rad, mCapsule.height, rad));
                else
                    return new Bounds(mCapsule.center, new Vector3(rad, rad, mCapsule.height));
            }
        }

        public override void GetBuildSource(int areaType, ICollection<NavMeshBuildSource> sources)
        {
            CapsuleCollider caps;
            if (!TryGetComponent(out caps))
                return;
            var src = new NavMeshBuildSource();
            src.shape = NavMeshBuildSourceShape.Capsule;
            src.size = new Vector3(caps.radius * 2, caps.height, caps.radius);
            src.area = this.areaType == 0 ? areaType : this.areaType;
            //src.sourceObject = b;
            Quaternion rot;
            if (caps.direction == 0) // z
                rot = Quaternion.Euler(0, 0, 90);
            else if (caps.direction == 1)
                rot = Quaternion.identity;
            else
                rot = Quaternion.Euler(90, 0, 0);
            src.transform = transform.localToWorldMatrix * Matrix4x4.TRS(caps.center, rot, Vector3.one);
            sources.Add(src);
        }

//#if UNITY_EDITOR

//        private void OnDrawGizmosSelected()
//        {
//            Gizmos.matrix = transform.localToWorldMatrix;
//            Gizmos.color = Color.gray * 0.8f;
//            var bd = localBounds;
//            Gizmos.DrawWireCube(bd.center, bd.size);
//        }

//#endif
    }
}